import logging
import os
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from models import AppUser

class AddUserHandler(webapp.RequestHandler):
	disallowed_shortnames = ['add_user', 'add_bookmark', 'delete_bookmark']

	def get(self):
		user = users.get_current_user()
		if not user:
			self.redirect(users.create_login_url("/add_user"))
			return
		
		query = AppUser.all().filter("user =", user)
		try:
			app_user = query.fetch(1)[0]
			#user already has a shortname
			self.redirect('/x')
			return
		except:
			path = os.path.join(os.path.dirname(__file__), 'add_user.html')
			self.response.out.write(template.render(path, {}))
			return
	
	def post(self):
		shortname = str(self.request.get("shortname"))

		if len(shortname) <= 2:
			path = os.path.join(os.path.dirname(__file__), 'add_user.html')
			data = {'messages': ["1-2 letter shortnames are reserved (sorry!)."]}
			self.response.out.write(template.render(path, data))
			return

		if shortname in self.disallowed_shortnames:
			path = os.path.join(os.path.dirname(__file__), 'add_user.html')
			data = {'messages': ["That shortname is not reserved."]}
			self.response.out.write(template.render(path, data))
			return
		
		query = AppUser.all().filter("shortname =", shortname)
		try:
			app_user = query.fetch(1)[0]
			# shortname exists
			path = os.path.join(os.path.dirname(__file__), 'add_user.html')
			data = {'messages': ["That username is already in use"]}
			self.response.out.write(template.render(path, data))
			return
		except:
			user = users.get_current_user()
			app_user = AppUser(user=user, shortname=shortname)
			app_user.put()
			logging.info("Added user %s with shortname %s" % (user, shortname))
			self.redirect('/x')
			return
	
def main():
	app = webapp.WSGIApplication([(r'.*', AddUserHandler)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)
	
if __name__ == "__main__":
	main()